import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { NzModalRef, NzMessageService, NzNotificationService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { SFSchema, SFUISchema } from '@delon/form';
import { Observable, of, zip } from 'rxjs';
import { catchError } from 'rxjs/operators';

/**
 * 数据源添加/修改
 */
@Component({
  selector: 'app-datasource-edit',
  templateUrl: './datasource-edit.component.html',
})
export class DataSourceEditComponent implements OnInit {
  // 驱动类型
  driverTypes = [];

  @Input()
  record: any = {};
  i: any;
  schema: SFSchema = {
    properties: {},
  };
  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 100,
      grid: { span: 12 },
    },
  };

  constructor(
    private modal: NzModalRef,
    private msgSrv: NzMessageService,
    public http: _HttpClient,
    private notice: NzNotificationService,
  ) {}

  ngOnInit(): void {
    const api = [this.http.get(`/cf/admin/dict/type/datasource_dirver_type`)];
    zip(...api)
      .pipe(
        catchError(([driverType]) => {
          return [driverType];
        }),
      )
      .subscribe(([driverType]) => {
        this.driverTypes = driverType.data;
        this.buildSf();
        if (this.record.id) {
          this.http.get(`/cf/admin/dsconf/${this.record.id}`).subscribe(res => {
            res.data.password = '';
            this.i = res.data;
          });
        }
      });
  }

  buildSf() {
    this.schema = {
      properties: {
        code: { type: 'string', title: '编码', ui: { autocomplete: 'off' } },
        name: { type: 'string', title: '名称', ui: { autocomplete: 'off' } },
        url: {
          type: 'string',
          title: 'jdbcUrl',
          ui: {
            widget: 'textarea',
            autosize: { minRows: 2, maxRows: 6 },
            grid: {
              span: 24,
            },
          },
        },
        username: { type: 'string', title: '用户名', ui: { autocomplete: 'off' } },
        password: { type: 'string', title: '密码', ui: { autocomplete: 'off' } },
        driver: { type: 'string', title: '驱动类型', enum: this.driverTypes },
      },
      required: ['code', 'name', 'url', 'username', 'driver'],
    };
  }

  save(value: any) {
    const req: Observable<string> = this.record.id
      ? this.http.put('/cf/admin/dsconf', value)
      : this.http.post(`/cf/admin/dsconf`, value);

    req.pipe(catchError(err => of(err))).subscribe(res => {
      if (res.status === 200) {
        this.notice.success('成功', '保存成功');
        this.modal.close(true);
      }
    });
  }

  close() {
    this.modal.destroy();
  }
}
